package com.amor.ui

import android.os.SystemClock
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.amor.app.BaseActivity
import com.amor.demo.web1.R
import com.amor.demo.web1.databinding.VMainBinding
import com.amor.ui.fragment.HomeFragment
import com.amor.ui.fragment.LaunchFragment
import com.amor.vm.BaseViewModel
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hy.frame.util.ActUtil

/**
 * title 主页
 * author HeYan
 * date 2021/9/25
 * desc
 */
class MainActivity : BaseActivity<VMainBinding, BaseViewModel>() {


    private var fragment: Fragment? = null

    override val layoutId: Int = R.layout.v_main

    override fun isFullscreen(): Boolean = true

    override fun initView() {

        //如果是首次主页，显示启动页
    }

    override fun initData() {
        //清空记录
        supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
        if (!isEnterMain()) {//首次进入
            fragment = LaunchFragment()
            supportFragmentManager.beginTransaction().add(R.id.container, fragment!!, "Launch").commitAllowingStateLoss()
            return
        }
        enterMain()
    }

    private fun isEnterMain(): Boolean {
        val value = curApp?.dataCache?.getValue(DATA_ENTER_MAIN)
        if (value != null)
            return value as Boolean
        return false
    }

    fun enterMain() {
        curApp?.dataCache?.putValue(DATA_ENTER_MAIN, true)
        if (true) {
            ActUtil.startAct(context, ProxyActivity::class.java)
            finish()
            return
        }
        //清除默认背景
        window.setBackgroundDrawableResource(R.color.background)
        //显示HOME
        val transaction = supportFragmentManager.beginTransaction()
        if (fragment != null) {
            transaction.remove(fragment!!)
        }
        fragment = HomeFragment()
        transaction.add(R.id.container, fragment!!, "Home").commitAllowingStateLoss()
        //重置状态栏
        ImmersionBar.with(this).transparentStatusBar().navigationBarColor(getNavigationBarColor())
            .statusBarDarkFont(false)
            .hideBar(BarHide.FLAG_SHOW_BAR)
            .init()


    }

    private var lastExitTime = 0L
    override fun onBackPressed() {
        if (fragment !is LaunchFragment) {
            val time = SystemClock.uptimeMillis()
            if (time - lastExitTime > EXIT_DELAY) {
                lastExitTime = time
                showToast("再按一次退出应用")
                return
            }
        }
        curApp?.exit()
    }

    companion object {
        private const val DATA_ENTER_MAIN = "ENTER_MAIN"
        private const val EXIT_DELAY = 2000L
    }
}